//
//  SDMethodTool.m
//  skinDetection
//
//  Created by  liangzhun on 2018/10/31.
//  Copyright © 2018年  liangzhun. All rights reserved.
//

#import "SDMethodTool.h"
#import <UMShare/UMShare.h>
#import <sys/utsname.h>
#import "SDSessionManager.h"
@implementation SDMethodTool

/**
 获取文本的高度

 @param text 文本
 @param width 文本的宽度
 @param font 文本字体的大小
 @return 文本对应的高度
 */
+ (float)getTextHeightWithText:(NSString *)text Width:(double)width Font:(UIFont *)font{
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
    
    
    return rect.size.height + 2;
    
}

/**
 获取文本的宽度
 
 @param text 文本
 @param height 文本的高度度
 @param font 文本字体的大小
 @return 文本对应的宽度
 */
+ (float)getTextWidthWithText:(NSString *)text Height:(double)height Font:(UIFont *)font
{
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(0, height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size.width + 2;
    
}
+ (NSInteger)getAttTextHeightWithText:(NSMutableAttributedString *)atttext withTextFontSize:(UIFont*)mFontSize Width:(double)width{
    CGSize size = [self getAttTextSizeWithText:atttext withTextFontSize:mFontSize WidthOrHeight:width isHeight:YES];
    return size.height + 2;
}
+ (NSInteger)getAttTextWidthWithText:(NSMutableAttributedString *)atttext withTextFontSize:(UIFont*)mFontSize Height:(double)height;{
 
    
    CGSize size = [self getAttTextSizeWithText:atttext withTextFontSize:mFontSize WidthOrHeight:height isHeight:NO];
    return size.width + 2;
}

/**
 根据文本的宽和高得到文本的大小

 @param content 文本
 @param mFontSize 文本字体的大小
 @param wh 宽或高
 @param height 调用这个方法想得到文本的高度或宽度
 @return 文本的大小
 */
+ (CGSize)getAttTextSizeWithText:(NSMutableAttributedString *)content withTextFontSize:(UIFont*)mFontSize WidthOrHeight:(double)wh isHeight:(BOOL)height
{

    [content addAttribute:NSFontAttributeName value:mFontSize range:NSMakeRange(0, content.length)];
    CGSize size = height? CGSizeMake(wh, MAXFLOAT):CGSizeMake(MAXFLOAT,wh );
    CGSize attSize = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    
    return attSize;
}
/**
 二维码图

 @param text 需要转换成二维码的文本
 @param width 二维码图片的大小
 @return 文本转换成二维码后生成的二维码图片
 */
+ (UIImage *)getQrCodeImageWithText:(NSString *)text Width:(CGFloat)width
{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //过滤器恢复默认
    [filter setDefaults];
    
    //将NSString格式转化成NSData格式
    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    //获取二维码过滤器生成的二维码
    CIImage *image = [filter outputImage];
    
    //将获取到的二维码添加到imageview上
    return [self createNonInterpolatedUIImageFormCIImage:image withSize:235];
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

/**
 获取xib的view

 @param viewName xib的文件名
 @return view
 */
+ (id)getViewWithViewName:(NSString *)viewName
{ 
    return [[NSBundle mainBundle] loadNibNamed:viewName owner:nil options:nil].lastObject;
}

/**
 获取StoryBoard中xib的ViewControl

 @param identifier StoryBoard中xib的Name
 @return ViewControl
 */
+ (id)getViewControlWithIdentifier:(NSString *)identifier
{
    return  [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:identifier];
}

/**
 微信第三方登陆

 @param vc 当前页面
 */
+ (void)loginWeChatWithViewController:(UIViewController *)vc action:(ActionBlock)block
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:vc completion:^(id result, NSError *error) {

        if (!error) {
            
            UMSocialUserInfoResponse *res = result;
            
            int sex =  [res.unionGender isEqualToString:@"男"]?0:1;
            NSString *header = [res.iconurl stringByReplacingOccurrencesOfString:@"/132" withString:@"/0"];
            
            NSDictionary *parame = @{@"appId":res.unionId,@"nickName":res.name,@"sex":[NSNumber numberWithInt:sex],@"headImage":header,@"device":[SDMethodTool iphoneType],@"appVer":APP_Version,@"imei":APP_DEVICE_UNIQUE};
            
            
            [SDNetwork postThirdLoginWithParameters:parame finish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
                
                 if (!error) {
                     
                  USERDEFAULT_REMOVE(KEY_USERMSG);
                  USERDEFAULT_PUT(dic[@"data"], KEY_USERMSG);
                  NSTimeInterval timeInt = [[NSDate date] timeIntervalSince1970];
                  USERDEFAULT_PUT([NSNumber numberWithDouble:timeInt], KEY_USERMSG_SAVETIME);
                  SDAppDelegate.userModel = [SDUserInformationModel modelObjectWithDictionary:dic[@"data"]];
                 
                  block();
                     
                 }
                
            }];
            
        }else{
//            LogString(error.description);
            //[self alertWithContent:error.description];
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:error.description preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertVC addAction:action];
            [vc presentViewController:alertVC animated:YES completion:nil];
            
        }
        
        //[NSSTRINGAPPEND(@"", @)
        
    }];
   
   
    
}

/**
 分享信息

 @param parame 需要分享的内容
 */
+ (void)shareMsgWithParame:(NSDictionary *)parame ViewController:(UIViewController *)vc
{
   
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        messageObject.text = @"创建网页内容对象";
        //创建网页内容对象
        NSString* thumbURL =  @"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLdahOa0ZXHdOfOq6mvdhrFU0iaO4QjsicpPeicVWDFBibkcffCYUwVx71ff8DEiciarI0hqmg9icMrGf6TQ/132";
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"美容仪" descr:@"美容仪 美容仪 美容仪 美容仪" thumImage:thumbURL];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@%@%@?id=%@",BASE_URL,INTERFACE_PREFIX,SD_API_ShareReport,parame[@"reportId"]];
    shareObject.thumbImage =  @"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLdahOa0ZXHdOfOq6mvdhrFU0iaO4QjsicpPeicVWDFBibkcffCYUwVx71ff8DEiciarI0hqmg9icMrGf6TQ/132";
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
    
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:vc completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
  
}

//获取设备的型号
+ (NSString *)iphoneType
{
    
    //需要导入头文件：#import <sys/utsname.h>
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    NSDictionary *dict = @{ // iPhone
                           @"iPhone5,3" : @"iPhone 5c", @"iPhone5,4" : @"iPhone 5c",@"iPhone6,1" : @"iPhone 5s", @"iPhone6,2" : @"iPhone 5s", @"iPhone7,1" : @"iPhone 6 Plus", @"iPhone7,2" : @"iPhone 6", @"iPhone8,1" : @"iPhone 6s", @"iPhone8,2" : @"iPhone 6s Plus", @"iPhone8,4" : @"iPhone SE", @"iPhone9,1" : @"iPhone 7", @"iPhone9,2" : @"iPhone 7 Plus", @"iPhone10,1" : @"iPhone 8", @"iPhone10,4" : @"iPhone 8", @"iPhone10,2" : @"iPhone 8 Plus", @"iPhone10,5" : @"iPhone 8 Plus", @"iPhone10,3" : @"iPhone X", @"iPhone10,6" : @"iPhone X", @"iPhone11,2" : @"iPhone XS", @"iPhone11,4" : @"iPhone XS Max", @"iPhone11,6" : @"iPhone XS Max", @"iPhone11,8" : @"iPhone XR", @"i386" : @"iPhone Simulator", @"x86_64" : @"iPhone Simulator", // iPad
                           @"iPad4,1" : @"iPad Air", @"iPad4,2" : @"iPad Air", @"iPad4,3" : @"iPad Air", @"iPad5,3" : @"iPad Air 2", @"iPad5,4" : @"iPad Air 2", @"iPad6,7" : @"iPad Pro 12.9", @"iPad6,8" : @"iPad Pro 12.9", @"iPad6,3" : @"iPad Pro 9.7", @"iPad6,4" : @"iPad Pro 9.7", @"iPad6,11" : @"iPad 5", @"iPad6,12" : @"iPad 5", @"iPad7,1" : @"iPad Pro 12.9 inch 2nd gen", @"iPad7,2" : @"iPad Pro 12.9 inch 2nd gen", @"iPad7,3" : @"iPad Pro 10.5", @"iPad7,4" : @"iPad Pro 10.5", @"iPad7,5" : @"iPad 6", @"iPad7,6" : @"iPad 6",
                           // iPad mini
                           @"iPad2,5" : @"iPad mini", @"iPad2,6" : @"iPad mini", @"iPad2,7" : @"iPad mini", @"iPad4,4" : @"iPad mini 2", @"iPad4,5" : @"iPad mini 2", @"iPad4,6" : @"iPad mini 2", @"iPad4,7" : @"iPad mini 3", @"iPad4,8" : @"iPad mini 3", @"iPad4,9" : @"iPad mini 3", @"iPad5,1" : @"iPad mini 4", @"iPad5,2" : @"iPad mini 4", // Apple Watch
                           @"Watch1,1" : @"Apple Watch", @"Watch1,2" : @"Apple Watch", @"Watch2,6" : @"Apple Watch Series 1", @"Watch2,7" : @"Apple Watch Series 1", @"Watch2,3" : @"Apple Watch Series 2", @"Watch2,4" : @"Apple Watch Series 2", @"Watch3,1" : @"Apple Watch Series 3", @"Watch3,2" : @"Apple Watch Series 3", @"Watch3,3" : @"Apple Watch Series 3", @"Watch3,4" : @"Apple Watch Series 3", @"Watch4,1" : @"Apple Watch Series 4", @"Watch4,2" : @"Apple Watch Series 4", @"Watch4,3" : @"Apple Watch Series 4", @"Watch4,4" : @"Apple Watch Series 4" };
    NSString *name = dict[platform];
    return name ? name : platform;
    
}

+ (void)alertWithContent:(NSString *)content handler:(void(^ __nullable)(UIAlertAction * _Nonnull action))handler
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:handler];
    [alertVC addAction:action];
    
    UIViewController *currentVC = [self getCurrentVC];
    [currentVC presentViewController:alertVC animated:YES completion:nil];
    
}

/**
 获取当前的ViewController

 @return 当前的ViewController
 */
+ (UIViewController *)getCurrentVC
{
    UIViewController *resultVC;
    resultVC = [self GetTopViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self GetTopViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
+ (UIViewController *)GetTopViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self GetTopViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self GetTopViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

/**
 判断是否是手机号码

 @param phoneNum 手机号码
 @return 否是手机号码
 */
+(BOOL)validateCellPhoneNumber:(NSString *)phoneNum
{
    
    /** * 手机号码: * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 16[6], 17[5, 6, 7, 8], 18[0-9], 170[0-9], 19[89]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705,198
     * 联通号段: 130,131,132,155,156,185,186,145,175,176,1709,166
     * 电信号段: 133,153,180,181,189,177,1700,199 */
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|6[6]|7[05-8]|8[0-9]|9[89])\\d{8}$";
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478]|9[8])\\d{8}$)|(^1705\\d{7}$)";
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|66|7[56]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    NSString *CT = @"(^1(33|53|77|8[019]|99)\\d{8}$)|(^1700\\d{7}$)";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    
    return ([regextestmobile evaluateWithObject:phoneNum] == YES) || ([regextestcm evaluateWithObject:phoneNum] == YES) || ([regextestct evaluateWithObject:phoneNum] == YES) || ([regextestcu evaluateWithObject:phoneNum] == YES);
    
}
#pragma mark - 当有提示时显示的log
+ (void)showWarnWithContent:(NSString *)content
{
    UIView *warnView = [[UIView alloc] init];
    warnView.layer.cornerRadius = 5.0;
    warnView.layer.masksToBounds = YES;
    warnView.alpha = 0.0;
    [warnView setBackgroundColor:[SDBlackColor colorWithAlphaComponent:0.7]];
    
    UILabel *lab = [[UILabel alloc] init];
    [lab setTextColor:SDWhiteColor];
    [lab setText:content];
    [lab setFont:Font(15)];
    [lab sizeToFit];
    
    UIViewController *nowVC = [self getCurrentVC];
    [nowVC.view addSubview:warnView];
    [warnView addSubview:lab];
    
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.mas_equalTo(10);
       
    }];
    CGSize size = lab.frame.size;
    [warnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(nowVC.view);
        make.size.mas_equalTo(CGSizeMake(size.width + 20, size.height + 20));
    }];
    
    [UIView animateWithDuration:0.2 animations:^{
        warnView.alpha = 1.0;
    }];
    [self performSelector:@selector(deleteWarnView:) withObject:warnView afterDelay:1.5];
}
+ (void)deleteWarnView:(UIView *)warnView
{
    [UIView animateWithDuration:0.1 animations:^{
        warnView.alpha = 0.3;
    } completion:^(BOOL finished) {
        [warnView removeFromSuperview];
    }];
    
}
@end
